package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

public class RequestProcessor extends Thread {

    private List<String> hosts;
    private Socket socket;
    private Map<String, Map<String, HttpServlet>> hostServletMap;

    public RequestProcessor(List<String> hosts, Socket socket, Map<String, Map<String, HttpServlet>> hostServletMap) {
        this.socket = socket;
        this.hostServletMap = hostServletMap;
        this.hosts = hosts;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            boolean found = false;
            String targetHost = null;
            if(request.getUrl().substring(1).split("/").length>1){
                targetHost = request.getUrl().substring(1).split("/")[0];
            }
            if(targetHost!=null)
            for(String host:hosts){
                if(targetHost.equals(host)) {
                    found = true;
                    Map<String, HttpServlet> servletMap = hostServletMap.get(host);
                    if(servletMap==null || servletMap.get(request.getUrl()) == null) {
                        response.outputHtml(host, request.getUrl());
                    }else{
                        // 动态资源servlet请求
                        HttpServlet httpServlet = servletMap.get(request.getUrl());
                        httpServlet.service(request,response);
                    }
                }
            }
            // if not found, try DEFAULT host
            if(!found){
                Map<String, HttpServlet> servletMap = hostServletMap.get(Bootstrap.DEFAULT_HOST);
                if(servletMap.get(request.getUrl()) == null) {
                    response.outputHtml(Bootstrap.DEFAULT_HOST, request.getUrl());
                }else{
                    // 动态资源servlet请求
                    HttpServlet httpServlet = servletMap.get(request.getUrl());
                    httpServlet.service(request,response);
                }
            }
            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
